<?
	include_once("includes/adodb/adodb.inc.php");
	
	function validateUser()
	{
		include_once("includes/mcrypt.php");
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$rsUser = $DB->Execute("SELECT * FROM users WHERE userState <> '$stateErase' AND idTypeUser = '$idTypeYoungMan' AND userName = '".$_REQUEST["userName"]."'");
			if($rsUser->EOF)
			{
				$userMesage = array("permission" => "DENIED");
				return json_encode($userMesage);
			}
			else
			{
				$mcrypt = new MCrypt();
				if($mcrypt->decrypt($rsUser->fields("userPassword")) == $mcrypt->decrypt($_REQUEST["userPassword"]))
				{
					$userMesage = array("permission" => "GRANT", 
										"idUser" => $rsUser->fields("idUser"),
										"userName" => $rsUser->fields("userName"),
										"userCompleteName" => $rsUser->fields("userCompleteName"),
										"userEMail" => $rsUser->fields("userEMail"),
										"idRestaurant" => $rsUser->fields("idRestaurant")
									   );
					return json_encode($userMesage);
				}
				else
				{
					$userMesage = array("permission" => "DENIED");
					return json_encode($userMesage);
				}
			}
		}
		catch (Exception $e)
		{
			return json_encode(array("permission" => "DENIED"));
		}
	}
	
	function getTables()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$strSQL = "SELECT T.* FROM tables T ".
					  "INNER JOIN assignedtables AT ON T.idTable = AT.idTable ".
					  "WHERE T.state <> '$stateErase'".
					  " AND AT.idUser = ".$_REQUEST["idUser"].
					  " AND T.idRestaurant = ".$_REQUEST["idRestaurant"];
						
			$rsTables = $DB->Execute($strSQL);
			
			$i = 0;
			if($rsTables->EOF)
				return json_encode(array());
			else {
				while(!$rsTables->EOF)
				{
					$arrJSON[$i]['idTable'] = $rsTables->fields("idTable");
					$arrJSON[$i]['description'] = $rsTables->fields("description");
					$arrJSON[$i]['state'] = $rsTables->fields("state");
					
					$rsTables->MoveNext();
					$i++;
				}
			}
			return json_encode($arrJSON);
		}
		catch (Exception $e)
		{
			return json_encode(array());
		}
	}
	
	function getFoodUpdate()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$sqlQuery = "SELECT f.idFood, f.description, f.idTypeFood, f.price, tf.idMenuFood FROM food f ".
					  "INNER JOIN typefood tf ON f.idTypeFood = tf.idTypeFood ".
					  "WHERE f.idRestaurant = ".$_REQUEST['idRestaurant'];
	
			$rsFoods = $DB->Execute($sqlQuery);
			
			$i = 0;
			while(!$rsFoods->EOF)
			{
				$arrJSON[$i]['idFood'] = $rsFoods->fields("idFood");
				$arrJSON[$i]['description'] = $rsFoods->fields("description");
				$arrJSON[$i]['idTypeFood'] = $rsFoods->fields("idTypeFood");
				$arrJSON[$i]['price'] = $rsFoods->fields("price");
				$arrJSON[$i]['idMenuFood'] = $rsFoods->fields("idMenuFood");
				
				$rsFoods->MoveNext();
				$i++;
			}
			
			return json_encode($arrJSON);
		}
		catch (Exception $e)
		{
			return json_encode(array());
		}
	}
	
	function getTypeFoodUpdate()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$sqlQuery = "SELECT * FROM typefood WHERE state <> '$stateErase' AND idRestaurant = ".$_REQUEST['idRestaurant'];
	
			$rsFoods = $DB->Execute($sqlQuery);
			
			$i = 0;
			while(!$rsFoods->EOF)
			{
				$arrJSON[$i]['idTypeFood'] = $rsFoods->fields("idTypeFood");
				$arrJSON[$i]['typeDescription'] = $rsFoods->fields("typeDescription");
				$arrJSON[$i]['idMenuFood'] =  $rsFoods->fields("idMenuFood");
				
				$rsFoods->MoveNext();
				$i++;
			}
			
			return json_encode($arrJSON);
		}
		catch (Exception $e)
		{
			return json_encode(array());
		}
	}
	
	function getOrder()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$sqlQuery = "SELECT * FROM orderfood WHERE state = '$stateTableBusy' AND idRestaurant = ".$_REQUEST['idRestaurant'];
			$rsFoods = $DB->Execute($sqlQuery);
			
			$i = 0;
			if($rsFoods->EOF)
				$arrJSON[$i]['status'] = "EOF";
			else
			{
				$arrJSON[$i]['status'] = "OK";
				while(!$rsFoods->EOF)
				{
					$arrJSON[$i]['idOrderFood'] = $rsFoods->fields("idOrderFood");
					$arrJSON[$i]['idTable'] = $rsFoods->fields("idTable");
					$arrJSON[$i]['numGuests'] =  $rsFoods->fields("numGuests");
					$arrJSON[$i]['state'] =  $rsFoods->fields("state");
					
					$sqlQuery = "SELECT * FROM orderfooditem WHERE idOrderFood = " . $rsFoods->fields("idOrderFood")." AND quantity > 0";
					$rsItem = $DB->Execute($sqlQuery);
					
					$j = 0;
					while(!$rsItem->EOF)
					{
						$arrJSON[$i]['items'][$j]['idOrderFoodItem'] = $rsItem->fields("idOrderFoodItem");
						$arrJSON[$i]['items'][$j]['idOrderFood'] = $rsItem->fields("idOrderFood");
						$arrJSON[$i]['items'][$j]['idFood'] = $rsItem->fields("idFood");
						$arrJSON[$i]['items'][$j]['quantity'] =  $rsItem->fields("quantity");
						$arrJSON[$i]['items'][$j]['price'] =  $rsItem->fields("price");
						$arrJSON[$i]['items'][$j]['state'] =  $rsItem->fields("state");
						
						$rsItem->MoveNext();
						$j++;
					}
					
					$rsFoods->MoveNext();
					$i++;
				}
			}
			
			return json_encode($arrJSON);
		}
		catch(Exception $e)
		{
			$arrJSON->status = "EOF";
			return json_encode($arrJSON);
		}
	}
	
	function setTableState()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$DB->StartTrans(); // iniciamos transaccion
			
			$strSQL = "UPDATE tables SET state = '".$_REQUEST['tableState']."' WHERE idTable = ".$_REQUEST['idTable'];
			$DB->Execute($strSQL);
			
			$strSQL = "UPDATE orderfood SET state = '".$_REQUEST['tableState']."' WHERE idTable = ".$_REQUEST['idTable']." AND state = '$stateTableBusy'";
			$DB->Execute($strSQL);
			
			if (!$DB->CompleteTrans())
				$arrJSON->status = "ERR";
			else
				$arrJSON->status = "OK";
			
			return json_encode($arrJSON);
		}
		catch(Exception $e)
		{
			$arrJSON->status = "ERR";
			return json_encode($arrJSON);
		}			
	}
	
	function getTableState()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
						
			$strSQL = "SELECT * FROM tables WHERE idTable = ".$_REQUEST['idTable'];
			$rsTable = $DB->Execute($strSQL);
			
			if(!$rsTable->EOF) {
				$joJSON->idTable = $rsTable->fields("idTable");
				$joJSON->description = $rsTable->fields("description");
				$joJSON->state = $rsTable->fields("state");
			}
			else {
				$joJSON = array();
			}
			
			return json_encode($joJSON);
		}
		catch(Exception $e)
		{
			return json_encode(array());
		}			
	}
	
	function setOrder()
	{
		include_once("includes/constants.php");
		
		try
		{
			$DB = NewADOConnection('mysqlt');
			$DB->Connect();
			$DB->Execute("SET NAMES utf8;");
			//$DB->debug=true;
			
			$jsonDataOrder = json_decode($_REQUEST['dataOrder'], true);
			$jsonDataOrderItem = json_decode($_REQUEST['dataOrderItem'], true);
	
			$DB->StartTrans(); // iniciamos transaccion
			
			$strSQL = "SELECT * FROM orderfood WHERE idTable = ".$jsonDataOrder[0]['idTable']." ORDER BY idOrderFood DESC";
			$rsOrder = $DB->Execute($strSQL);
			
			if($rsOrder->fields("state") == $stateTableFree || $rsOrder->fields("state") == $stateTableClose || $rsOrder->EOF)
			{
				$strSQL = "INSERT INTO orderfood (";
				$strSQL .= "idTable, ";
				$strSQL .= "numGuests, ";
				$strSQL .= "state, ";
				$strSQL .= "idRestaurant";
				$strSQL .= ") VALUES (";
				$strSQL .= $jsonDataOrder[0]['idTable'] . ", ";
				$strSQL .= $jsonDataOrder[0]['numGuest'] . ", ";
				$strSQL .= "'".$jsonDataOrder[0]['state']."',";
				$strSQL .= $jsonDataOrder[0]['idRestaurant'];
				$strSQL .= ")";
				
				$DB->Execute($strSQL);
				
				$order_ID = $DB->Insert_ID();
			}
			else
				$order_ID = $rsOrder->fields("idOrderFood");
			
			$arrFoodsIds = '';
			foreach ($jsonDataOrderItem as $jsonItem)
			{
				$strSQL = "SELECT * FROM orderfooditem WHERE idOrderFood = ".$order_ID." AND idFood = ".$jsonItem['idFood'];
				$rsOrderItem = $DB->Execute($strSQL);
				
				if($rsOrderItem->EOF) {
					$strSQL = "INSERT INTO orderfooditem (";
					$strSQL .= "idOrderFood, ";
					$strSQL .= "idFood, ";
					$strSQL .= "quantity, ";
					$strSQL .= "price, ";
					$strSQL .= "state ";
					$strSQL .= ") VALUES (";
					$strSQL .= $order_ID . ", ";
					$strSQL .= $jsonItem['idFood'] . ", ";
					$strSQL .= $jsonItem['quantity'] . ", ";
					$strSQL .= $jsonItem['price'] . ", ";
					$strSQL .= "'".$stateOrderSubmitted . "'";
					$strSQL .= ")";
					
					$DB->Execute($strSQL);
				}
				$arrFoodsIds .= $jsonItem['idFood'].",";
			}
	
			$arrFoodsIds = substr($arrFoodsIds,0,-1);
			
			//Actualizo todo lo que se borro en la Tablet
			$strSQL = "SELECT * FROM orderfooditem WHERE idOrderFood = ".$order_ID." AND idFood NOT IN ($arrFoodsIds)";
			$rsOrderItem = $DB->Execute($strSQL);
			
			while(!$rsOrderItem->EOF) {
				$DB->Execute("UPDATE orderfooditem SET quantity = quantity * -1, price = price * -1 WHERE idOrderFoodItem = ".$rsOrderItem->fields('idOrderFoodItem'));
				$rsOrderItem->MoveNext();
			}
			
			if (!$DB->CompleteTrans())
				$arrJSON->status = "ERR";
			else
				$arrJSON->status = "OK";
			
			return json_encode($arrJSON);
		}
		catch(Exception $e)
		{
			$arrJSON->status = "ERR";
			return json_encode($arrJSON);
		}
	}
	
	
	switch($_REQUEST['action'])
	{
		case "validateUser":
			echo validateUser();
			break;
		case "getTables":
			echo getTables();
			break;
		case "getFoodUpdate":
			echo getFoodUpdate();
			break;
		case "getTypeFoodUpdate":
			echo getTypeFoodUpdate();
			break;
		case "getOrder":
			echo getOrder();
			break;
		case "setOrder":
			echo setOrder();
			break;
		case "setTableState":
			echo setTableState();
			break;
		case "getTableState":
			echo getTableState();
			break;
	}
?>